from rest_framework_jwt.settings import api_settings


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'id': user.id,
        'username': user.username,
        'avatar': user.avatar
    }


# 自定义分页类
from collections import OrderedDict

from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response


class StandardResultPagination(PageNumberPagination):
    """自定义分页类"""
    # 指定分页默认页容量
    page_size = 5
    # 指定获取分页数据时指定`页容量`的参数名称
    page_size_query_param = 'pagesize'
    # 指定分页最大页容量
    max_page_size = 20

    def get_paginated_response(self, data):
        """重写父类方法，自定义分页响应数据格式"""
        return Response(OrderedDict([
            ('counts', self.page.paginator.count),
            ('lists', data),
            ('page', self.page.number),
            ('pages', self.page.paginator.num_pages),
            ('pagesize', self.get_page_size(self.request))
        ]))


def get_token(user_obj):
    # 组织payload数据的方法
    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    # 生成jwt token数据的方法
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

    # 组织payload数据
    payload = jwt_payload_handler(user_obj)
    # 生成jwt token
    token = jwt_encode_handler(payload)

    return token
